package edu.hawaii.halealohacli.command;

import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;

/**
 * Tests correctness of the RepeatedCommand behavior that is to be 
 * inherited/used by other commands. 
 * 
 * @author Zach Tomaszewski
 */
public class TestRepeatedCommand { 
  
  /**
   * Makes sure it works.
   * 
   * @throws InterruptedException  If this test thread is interrupted.
   */
  @Test
  public void test() throws InterruptedException {
    //setup
    FakeInputStream fake = new FakeInputStream();
    final RepeatedCounter task = new RepeatedCounter();
    task.input = fake; 

    //execute in separate (anonymous) thread because it blocks
    new Thread() {
      @Override
      public void run() {
        task.execute(1);  //exec every second 
      }      
    }
    .start();  //(stupid Checkstyle won't let me put this on previous line)
    
    Thread.sleep(2200); //wait two seconds and a bit
    fake.hasInput = true;  //simulate user input

    //exec + (1 sec) + exec + (1 sec) + exec = 3 times in 2 secs
    assertEquals("job executed 3 times", 3, task.counter);
  }
  
  /**
   * A command that just increments an internal counter each time it is 
   * executed.
   */
  private static class RepeatedCounter extends RepeatedCommand {
    int counter = 0;

    @Override
    public void doTask() {
      counter++;      
    }        
  }

  /**
   * A fake input stream to substitute for System.in.
   */
  private static class FakeInputStream extends InputStream {
    boolean hasInput = false;
    
    @Override
    public int read() throws IOException {      
      return 1;
    }
    
    @Override
    public int available() {
      return (hasInput) ? 1 : 0;
    }
  }
}
